package com.example.JavaWebApi.core.controlleradvice;

import com.example.JavaWebApi.core.commonmodel.Exceptions.BusinessException;
import com.example.JavaWebApi.core.commonmodel.ResponseModel;
import com.example.JavaWebApi.core.commonmodel.ResponseTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @program: java-web-api
 * @description: 异常处理
 * @author: 杨泽
 * @create: 2022-10-10 14:14
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler({BindException.class})
    public ResponseModel<String> MethodArgumentNotValidException(BindException exception){
        List<ObjectError> objectErrors=exception.getBindingResult().getAllErrors();
        StringBuilder sb=new StringBuilder();
        for(ObjectError error : objectErrors){
            sb.append(error.getDefaultMessage()+",");
        }
        log.error(sb.toString());
        return new ResponseModel<>(ResponseTypeEnum.ErrorParameter,sb.toString());
    }
    @ExceptionHandler({IllegalStateException.class})
    public ResponseModel<String> IllegalStateException(IllegalStateException exception){
        log.error(exception.getMessage());
        return new ResponseModel<>(ResponseTypeEnum.ErrorParameter,exception.getMessage());
    }
    @ExceptionHandler({BusinessException.class})
    public ResponseModel<String> BusinessException(BusinessException exception){
        log.error(exception.getMessage());
        return new ResponseModel<>(exception.getResponseTypeEnum(),exception.getMessage());
    }
    @ExceptionHandler({Error.class})
    public ResponseModel<String> Error(Error error){
        log.error(error.getMessage());
        return new ResponseModel<>(ResponseTypeEnum.Exception, error.getMessage());
    }
    @ExceptionHandler({Exception.class})
    public ResponseModel<String> Exception(Exception exception){
        log.error(exception.getMessage());
        return new ResponseModel<>(ResponseTypeEnum.Exception, exception.getMessage());
    }
}